const express = require('express');
const cors = require('cors');
const helmet = require('helmet');

const app = express();
const PORT = process.env.PORT || 3000;

// 导入数据库配置和路由
const { checkSequelizeConnection } = require('./library/sequelize.js');
const { initModel: initUserModel } = require('./models/user.js');
const { initModel: initTokenModel } = require('./models/token.js');
const { initModel: initRoleModel } = require('./models/role.js');
const { initModel: initVoteModel } = require('./models/vote.js');
const { initModel: initVoteEntryModel } = require('./models/voteEntry.js');
const { initModel: initVoteExtraModel } = require('./models/voteExtra.js');
const { initModel: initVoteRecordModel } = require('./models/voteRecord.js');
const { initModel: initVoteUserModel } = require('./models/voteUser.js');
const { initModel: initNoteModel } = require('./models/note.js');
const { configureLogger } = require('./library/logger.js');
const { globalErrorHandler, notFoundHandler } = require('./middleware/responseHandler.js');
const cmsUserRoute = require('./routes/cms/user.js');
const cmsRoleRoute = require('./routes/cms/role.js');
const miniUserRoute = require('./routes/mini/user.js');
const miniVoteRoute = require('./routes/mini/vote.js');
const miniVoteEntryRoute = require('./routes/mini/voteEntry.js');
const miniNoteRoute = require('./routes/mini/note.js');
const commonCOSRoute = require('./routes/common/cos.js');

// 中间件
app.use(helmet()); // 安全头
app.use(cors()); // CORS支持
app.use(configureLogger()); // 高级日志系统
app.use(express.json()); // JSON解析
app.use(express.urlencoded({ extended: true })); // URL编码解析

// 根路由
app.get('/', (req, res) => {
    res.json({
        message: '欢迎使用Legendary API',
        version: '1.0.0',
        status: 'running',
        features: [
            'Express.js框架',
            'Sequelize ORM',
            'CORS支持',
            '安全头设置',
            '请求日志',
            'CMS后台管理',
            '用户管理',
            '角色管理',
            '小程序用户管理',
            '微信小程序登录',
            '投票管理',
            '投票作品管理',
            '投票额外计数管理',
            '投票记录管理',
            '投票用户管理',
            '留言板管理',
            '通用COS权限分发'
        ],
        endpoints: {
            health: '/health',
            test: '/api/test',
            'cms-user': '/cms/user',
            'cms-role': '/cms/role',
            mini: '/mini',
            'mini-vote': '/mini/vote',
            'mini-voteEntry': '/mini/voteEntry',
            'mini-note': '/mini/note',
            'common-cos': '/common/cos'
        }
    });
});

// 健康检查路由
app.get('/health', (req, res) => {
    res.json({
        status: 'OK',
        timestamp: new Date().toISOString(),
        data: {
            id: 1,
            name: '测试数据',
            timestamp: new Date().toISOString()
        }
    });
});

// CMS后台路由（按模块分别注册）
app.use('/cms/user', cmsUserRoute);
app.use('/cms/role', cmsRoleRoute);

// 小程序路由
app.use('/mini/user', miniUserRoute);
app.use('/mini/vote', miniVoteRoute);
app.use('/mini/voteEntry', miniVoteEntryRoute);
app.use('/mini/note', miniNoteRoute);

// 通用接口路由
app.use('/common/cos', commonCOSRoute);

// 404处理
app.use(notFoundHandler);

// 全局错误处理中间件
app.use(globalErrorHandler);

// 启动服务器
app.listen(PORT, async () => {
    console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
    console.log(`📊 健康检查: http://localhost:${PORT}/health`);
    console.log(`🧪 API测试: http://localhost:${PORT}/api/test`);
    console.log(`👤 用户管理: http://localhost:${PORT}/cms/user`);
    console.log(`👥 角色管理: http://localhost:${PORT}/cms/role`);
    console.log(`📱 小程序端: http://localhost:${PORT}/mini`);
    console.log(`🗳️ 投票管理: http://localhost:${PORT}/mini/vote`);
    console.log(`🎨 投票作品: http://localhost:${PORT}/mini/vote-entry`);
    console.log(`📝 留言板管理: http://localhost:${PORT}/mini/note`);
    console.log(`☁️ 通用COS: http://localhost:${PORT}/common/cos`);

    // 启动时测试数据库连接
    console.log('\n🔍 正在测试数据库连接...');

    // 测试Sequelize连接
    const sequelizeConnected = await checkSequelizeConnection();
    if (sequelizeConnected) {
        // 初始化模型
        const userModelInitialized = await initUserModel();
        const tokenModelInitialized = await initTokenModel();
        const roleModelInitialized = await initRoleModel();
        const voteModelInitialized = await initVoteModel();
        const voteEntryModelInitialized = await initVoteEntryModel();
        const voteExtraModelInitialized = await initVoteExtraModel();
        const voteRecordModelInitialized = await initVoteRecordModel();
        const voteUserModelInitialized = await initVoteUserModel();
        const noteModelInitialized = await initNoteModel();

        if (userModelInitialized && tokenModelInitialized && roleModelInitialized && voteModelInitialized && voteEntryModelInitialized && voteExtraModelInitialized && voteRecordModelInitialized && voteUserModelInitialized && noteModelInitialized) {
            console.log('✅ 数据库和模型初始化完成');
        } else {
            console.log('❌ 模型初始化失败');
        }
    } else {
        console.log('❌ 数据库连接失败，请检查配置');
    }
});

module.exports = app;